const app = getApp()
const db = wx.cloud.database()
const to = app.require("lib/awaitTo")
const upload = app.require("lib/upload")

Page({
    data: {
        loading: false,
        form: {}
    },
    onLoad() {
        this.setData({ form: wx.getStorageSync('user') })
    },
    chooseImg() {
        wx.chooseImage({
            count: 1,
            sizeType: ['compressed', 'original'], //可以指定是原图还是压缩图，默认二者都有
            sourceType: ['album', 'camera'], //从相册选择
            success: (res) => {
                this.setData({ 'form.avatarUrl': res.tempFilePaths[0] })
            }
        });
    },
    contentInput(e) {
        const type = e.currentTarget.dataset.type
        this.setData({ ['form.' + type]: e.detail.value })
    },
    async submit() {
        this.setData({ loading: true })
        let { avatarUrl, nickName, intro } = this.data.form
        const urlProtocol = this.getProtocol(this.data.form.avatarUrl)
        if (urlProtocol === "http") {
            var uploadRes = await upload(this.data.form.avatarUrl)
            avatarUrl = uploadRes.fileID
        }
        const [err] = await to(db.collection('user')
            .doc(this.data.form._id).
            update({
                data: {
                    avatarUrl,
                    nickName,
                    intro
                }
            }))
        this.setData({ loading: false })
        if (err) { return }
        wx.setStorageSync('user', this.data.form)
        app.globalData.pubSub.publish("onUserUpdate")
        await wx.navigateBack()
        wx.showToast({
            icon: "none",
            title: '已保存',
        })
    },
    getProtocol(url) {
        return url.split(":")[0]
    }
})